package com.liuya.log.interceptor;

import com.liuya.interceptor.BaseInterceptor;
import com.liuya.log.SysEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.NamedThreadLocal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器，拦截用户请求记录到日志表中
 *
 * @author liuya
 * @date 20160824
 */
public class LogInterceptor extends BaseInterceptor {
    @Autowired
    @Qualifier("sysEventServiceImpl")
    private SysEventService sysEventService;

    private final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 开始时间（该数据只有当前请求的线程可见）
        startTimeThreadLocal.set(System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
//        System.out.println(AopUtils.isAopProxy(sysEventService));
//        System.out.println(AopUtils.isCglibProxy(sysEventService));
//        System.out.println(AopUtils.isJdkDynamicProxy(sysEventService));
        // 保存日志
        sysEventService.saveEvent(request, response, ex, startTimeThreadLocal.get(), System.currentTimeMillis());
        super.afterCompletion(request, response, handler, ex);
    }
}
